package algorithms.leaning.class01;

import common.util.MyUtil;

/**
 * 在一个有序数组中，找<=某个数最右侧的位置
 * 1,2,2,2,2,2,3,4,5,7,8,10 2最右的位置就是5
 *
 * @author guichang
 * @date 2021/5/30
 */

@SuppressWarnings("all")
public class Code6_二分_右侧 {

    public static void main(String[] args) {
        int[] nums = MyUtil.createArray(1, 1, 2, 2, 2, 2, 2, 3, 4, 5, 7, 8, 10);
        int index = binarySearchLeft(nums, 2); // 5
        MyUtil.print(index);
    }

    public static int binarySearchLeft(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0, right = nums.length - 1, mid, result = -1;
        while (left <= right) {
            mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                result = mid;
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return result;
    }
}